//
//  SEGAdressListViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/9.
//

#import "SEGAdressListViewModel.h"

@implementation SEGAdressListViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createSignal];
        [self seg_createDeleteAddressCommand];
        [self seg_createNormalAddressCommand];
        [self seg_createUpdateAddressCommand];
    }
    return self;
}
// 查询地址列表
- (void)seg_createSignal {
    @weakify(self);
    self.signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.myManager requestMyAddressFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                [self.myManager.seg_segaddressmodel enumerateObjectsUsingBlock:^(SEGAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.defaultType isEqualToString:@"1"]) { // 更新默认配送地址
                        [SEGProfileManager sharedManager].profile.addressId = obj.id;
                        [SEGProfileManager sharedManager].profile.defaultAddress = obj.userAddress;
                        *stop = YES;
                    }
                }];
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            } else {
                if (self.myManager.seg_segaddressmodel.count == 0) { // 更新默认配送地址
                    [SEGProfileManager sharedManager].profile.addressId = @"";
                    [SEGProfileManager sharedManager].profile.defaultAddress = @"";
                }
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                [subscriber sendError:error];
            }
        }];
        return nil;
    }];
}
// 删除地址
- (void)seg_createDeleteAddressCommand {
    @weakify(self);
    self.deleteAddressCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *addressId) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.myManager requestDeleteAddressByid:addressId Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    [subscriber sendNext:@""];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }];
}
// 设置默认地址
- (void)seg_createNormalAddressCommand {
    @weakify(self);
    self.normalAddressCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *addressId) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.myManager requestSetDefaultAddressByid:addressId Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                // 更新默认配送地址
                [self.myManager.seg_segaddressmodel enumerateObjectsUsingBlock:^(SEGAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([addressId isEqualToString:obj.id]) { // 更新默认配送地址
                        [SEGProfileManager sharedManager].profile.addressId = obj.id;
                        [SEGProfileManager sharedManager].profile.defaultAddress = obj.userAddress;
                        *stop = YES;
                    }
                }];

                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }];
}
- (void)seg_createUpdateAddressCommand {
    @weakify(self);
    self.updateAddressCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *winnerId) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            // BUG:34712 【5.0.0】领取奖品，接口已返回失败msg=中奖记录不存在或不属于该用户；返回列表页，再点击该中奖记录，显示领取成功的记录信息
            // 选择地址的入口为，任务-中奖纪录详情-线上实物
            if (self.channel && [self.channel isKindOfClass:[NSString class]] && [self.channel isEqualToString:@"2"]) {
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params setValue:self.currentAddress.contactPhone forKey:@"tel"];
                [params setValue:self.currentAddress.contactName forKey:@"addressee"];
                [params setValue:self.currentAddress.userAddress forKey:@"address"];
                NSString *paramsString = [params yy_modelToJSONString];
                
                [[SEGReceiveprizeManager sharedManager] requestReceiveprizeWithRecordid:winnerId winnerDetail:paramsString finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        [subscriber sendNext:@""];
                        [subscriber sendCompleted];
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
            }else {
                [self.myManager requestUpdateAddrByWinnerId:winnerId reciveName:self.currentAddress.contactName reciveTel:self.currentAddress.contactPhone reciveAddr:self.currentAddress.userAddress finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        [subscriber sendNext:@""];
                        [subscriber sendCompleted];
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
            }
            return nil;
        }];
    }];
}

#pragma mark - Getter
- (SEGMyManager *)myManager {
    if (!_myManager) _myManager = [[SEGMyManager alloc] init];
    return _myManager;
}

@end
